package com.google.code.motoo.sample.press;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class XClient {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws Exception {
		int size = 2000;
		ExecutorService service = Executors.newFixedThreadPool(size);
		for (int i=0;i<size;i++) {
			service.submit(new Work(new Socket("192.168.1.205", 9000)));
			Thread.sleep(50);
		}
		Thread.sleep(Integer.MAX_VALUE);
	}
	
	static class Work implements Runnable {
		
		Socket socket;
	    BufferedReader in;
	    PrintWriter out; 
	    
	    public Work() {
	    }
	    
	    public Work(Socket socket) {
	    	this.socket = socket;
	    	
	    }

		public void run() {
            try {
				//从页面上接收输入
            	socket.setKeepAlive(true);
            	socket.setReuseAddress(true);
				out = new PrintWriter(socket.getOutputStream(), true);
				new ReadThread(socket).start();
			} catch (IOException e) {
				e.printStackTrace();
			} 
			
			while (true) {
				try {
					out.println("TODO Auto-generated catch block");
					Thread.sleep(60 * 1000);
				} catch (Exception e) {
					try {
						out.close();
						in.close();
						socket.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					e.printStackTrace();
				}
				
			}
			
		}
	}
	
	static class ReadThread extends Thread {
		private Socket socket;
		static BufferedReader in;
		
		public ReadThread(Socket socket) throws IOException {
			this.socket = socket;
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		}
		
		@Override
		public void run() {
			while(true) {
		    	try {
					String content = in.readLine();
					if (content != null && !content.trim().equals(""))
						System.out.println(content);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}
